package model

import entity.MyContract.CONVERTED_HTML_PATH
import entity.PbcEbookEntity
import presenter.MainPresenter
import util.MyDbHelper
import util.OfficeExcuse
import java.io.File


class PbcEbooksModel {

    fun getAllEbooks(): List<PbcEbookEntity> {
        try {
            val ebooks = MyDbHelper.instance.selectAllEbooks()
            return ebooks
        } finally {
            MyDbHelper.instance.onClose()
        }

    }


    fun getParentPath(currentPath: String, isDir: Boolean): String {

        return if (!isDir) currentPath.substring(0, currentPath.lastIndexOf("/")) else currentPath
    }



    fun removeOldFiles(filePath: String) {
        if (!File(filePath).exists()) return
        val foldPath = filePath.substring(0, filePath.lastIndexOf("/"))
        if (File(foldPath).exists())
            File(foldPath).deleteRecursively()
    }

    fun updateBookContentIntoDb(newFile: File, oldeBook: PbcEbookEntity): List<PbcEbookEntity> {

        val newBook = oldeBook.copy(content = newFile.path)

        val resultcode = MyDbHelper.instance.updateEbookById(oldeBook.id, newBook)

        return listOf(newBook)
    }


    fun updateBookNameIntoDb(newName: String, oldeBook: PbcEbookEntity): Int {


        val result =  MyDbHelper.instance.updateEbookById(id = oldeBook.id, newEbook = oldeBook.copy(name = newName))

        MyDbHelper.instance.onClose()

        return result
    }


    fun changeWordToHtml(importFiles: List<File>, parentPath: String): List<File> {
        val convertedFiles = mutableListOf<File>()

        importFiles.forEach {
            val filePath = CONVERTED_HTML_PATH + parentPath + "/" + it.nameWithoutExtension + "/"
            val isSuccess = OfficeExcuse.wordToHtml(filePath, it)
            if (isSuccess) {
                convertedFiles.add(File(filePath + it.nameWithoutExtension + ".html"))
            }
        }
        return convertedFiles
    }

    fun addNewBooksToDb(importFiles: List<File>, parentPath: String): List<PbcEbookEntity> {
        val importEbooks = mutableListOf<PbcEbookEntity>()
        importFiles.forEach {
            importEbooks.add(
                    PbcEbookEntity(
                            0,
                            it.nameWithoutExtension,
                            parentPath + "/" + it.nameWithoutExtension,
                            false,
                            it.path))
        }
        return MyDbHelper.instance.insertEbooks(importEbooks)
    }


    fun addNewFoldIntoDb(pbcEbookEntity: PbcEbookEntity): Int{
        try {
            return MyDbHelper.instance.insertEbook(pbcEbookEntity)
        } finally {
            MyDbHelper.instance.onClose()
        }
    }

    fun removeEbooks(removeBooks: PbcEbookEntity){
        MyDbHelper.instance.deleteEbookByPath(removeBooks.path)
    }


}